package com.iwhalecloud.bss.kite.cucc.service.pos.handler.impl;

import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.client.dto.pos.KitePosControlDTO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.iwhalecloud.bss.kite.cucc.client.dto.pos.KitePosRequestDTO;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalInfConsts;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalKeyConsts;
import com.iwhalecloud.bss.kite.cucc.service.pos.handler.CuccPosServiceUtils;
import com.iwhalecloud.bss.kite.cucc.service.pos.handler.IKitePosSceneHandler;
import com.iwhalecloud.bss.kite.cucc.service.pos.handler.KitePosHandlerContext;
import com.iwhalecloud.bss.kite.cucc.service.util.LocalSerialNumUtil;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.inst.KiteSceneInst;
import com.ztesoft.bss.common.util.SpringUtil;

import java.util.Map;
import java.util.Optional;

@Service
public class KitePosRequestHandler implements IKitePosSceneHandler {

	@Override
	public void handle(KitePosHandlerContext context) {
		IQuerySceneInstService querySceneInstService = SpringUtil.getBean(IQuerySceneInstService.class);
		KiteSceneInst sceneInst = querySceneInstService.getSceneInst(context.getSceneInstId());
		if (!StringUtils.equalsAny(sceneInst.getOperType(), LocalKeyConsts.SCENE_OPER_TYPE_ORDER_SIGN)) {
			KitePosRequestDTO request = new KitePosRequestDTO();
            KitePosControlDTO control = new KitePosControlDTO();

            // 订单来源、原单id，首先从订单详情中获取，没有就传运营平台-销售模块
            KitePosRequestDTO requestDto = Optional.ofNullable((KitePosRequestDTO) querySceneInstService.getExtParameterValue(context.getSceneInstId(), "requestDto")).orElse(new KitePosRequestDTO());
            request.setSourceOrderId(StringUtils.isEmpty(requestDto.getSourceOrderId()) ? sceneInst.getCustOrderId() : requestDto.getSourceOrderId());
            String sourceMall = requestDto.getSourceMall();
            String sourceMallName = requestDto.getSourceMallName();
            if(KiteStringUtils.isEmpty(sourceMall)) {
                sourceMall = "24";
                sourceMallName = "运营平台";
            }

            request.setSourceMall(sourceMall);
            if(KiteStringUtils.isNotEmpty(sourceMallName)) {
                request.setSourceMallName(sourceMallName);
            }
			request.setVersion(1);
			if(CuccPosServiceUtils.isRouteUser(context.getSceneInstId(),context.getCustId())) {
				request.setAppId(LocalInfConsts.APP_ID);
			}
			request.setSerialNo(LocalSerialNumUtil.getOrderSerialNo());
			if(KiteStringUtils.isEqual(sceneInst.getAskSource(), LocalKeyConsts.ASK_SOURCE_ORDER)){
                control.setUpdateMethod("1");
                request.setControl(control);
            }
			context.getPosDto().setRequest(request);
		}
	}

}
